<template>
  <lay-card>
    <lay-table v-bind="$attrs" :page="page" :height="$attrs.height || '450px'"

      :even="$attrs.even == undefined ? true : $attrs.even" :columns="columns" :loading="isLoading"

      :default-toolbar="$attrs.defaultToolbar || true" :data-source="tableData">

      <template v-for="slotName in Object.keys($slots)" v-slot:[slotName]="slotProps">
        <slot :name="slotName" v-bind="slotProps"></slot>
      </template>
    </lay-table>
  </lay-card>
</template>


<script setup>
import { BASE_URL } from "@/libs/constants";
import { $http } from "@/api";
import { reactive, ref, watchEffect } from "vue";
import Message from "@/libs/message";
const props = defineProps({
  url: String, //url
  defaultParams: {
    type: Object,
    default: {},
  }, //请求参数
  columns: Array, //表头
  defaultCellWidth: {
    //单元格默认宽度
    type: String,
    default: "80",
  },
  method: {
    //请求方式
    type: String,
    default: "GET",
  },
});

// ----------------------------------------------分页区域

// 分页
const page = reactive({ current: 1, limit: 10, total: 0 });

// 给单元格添加默认宽度
props.columns.forEach((e) => {
  if (e.width == undefined) {
    e.width = props.defaultCellWidth + "px";
  }
});

// -----------------------------------------------------表格区域

// 是否显示加载状态
const isLoading = ref(false);

// 表格数据
const tableData = ref([]);

// 默认参数
const defaultParams = ref(props.defaultParams);

// 渲染表格
function render() {
  // 开启加载状态
  isLoading.value = true;
  // 请求方式
  const method = props.method.toLowerCase();
  // url
  const url = BASE_URL + "/api/" + props.url;
  // 开始请求数据
  $http[method](url, {
    ...defaultParams.value,
    page: page.current,
    limit: page.limit,
  })
    .then((res) => {
      if (res.code === 0) {
        tableData.value = res.data;
        page.total = res.count;
      } else {
        Message.error(res.msg);
      }
    })
    .catch((err) => {
      console.log(err);
    })
    .finally(() => {
      isLoading.value = false;
    });
}
// 监听变量
watchEffect(() => {
  render();
});

// 暴露组件的行为
defineExpose({
  //重载
  reload(obj = { ...defaultParams.value }) {
    defaultParams.value = obj;
  },
});
</script>

<style scoped lang="less"></style>